package com.fancy.recommendation.controller;

import com.fancy.common.dto.response.Result;
import com.fancy.recommendation.dto.request.UserBehaviorRequestDTO;
import com.fancy.recommendation.entity.UserBehavior;
import com.fancy.recommendation.entity.UserPreference;
import com.fancy.recommendation.service.UserBehaviorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 用户行为控制器
 *
 * @author fancy
 */
@Api(tags = "用户行为分析")
@Slf4j
@RestController
@RequestMapping("/api/v1/user-behaviors")
@RequiredArgsConstructor
public class UserBehaviorController {

    private final UserBehaviorService userBehaviorService;

    @ApiOperation(value = "记录用户行为", notes = "记录用户的操作行为")
    @PostMapping
    public Result<Void> recordBehavior(@Valid @RequestBody UserBehaviorRequestDTO request) {
        try {
            userBehaviorService.recordBehavior(request);
            return Result.success(null);
        } catch (Exception e) {
            log.error("记录用户行为失败: {}", request, e);
            return Result.fail("记录行为失败");
        }
    }

    @ApiOperation(value = "批量记录用户行为", notes = "批量记录用户的操作行为")
    @PostMapping("/batch")
    public Result<Void> batchRecordBehaviors(@Valid @RequestBody List<UserBehaviorRequestDTO> requests) {
        try {
            userBehaviorService.batchRecordBehaviors(requests);
            return Result.success(null);
        } catch (Exception e) {
            log.error("批量记录用户行为失败: 数量={}", requests.size(), e);
            return Result.fail("批量记录行为失败");
        }
    }

    @ApiOperation(value = "获取用户行为统计", notes = "获取用户的行为统计信息")
    @GetMapping("/stats/{userId}")
    public Result<Map<String, Object>> getUserBehaviorStats(
            @ApiParam(value = "用户ID", required = true) @PathVariable Long userId) {
        try {
            Map<String, Object> stats = userBehaviorService.getUserBehaviorStats(userId);
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取用户行为统计失败: userId={}", userId, e);
            return Result.fail("获取行为统计失败");
        }
    }

    @ApiOperation(value = "获取用户最近行为", notes = "获取用户最近的操作行为")
    @GetMapping("/recent/{userId}")
    public Result<List<UserBehavior>> getRecentBehaviors(
            @ApiParam(value = "用户ID", required = true) @PathVariable Long userId,
            @ApiParam(value = "数量限制") @RequestParam(defaultValue = "20") Integer limit) {
        try {
            List<UserBehavior> behaviors = userBehaviorService.getRecentBehaviors(userId, limit);
            return Result.success(behaviors);
        } catch (Exception e) {
            log.error("获取用户最近行为失败: userId={}", userId, e);
            return Result.fail("获取最近行为失败");
        }
    }

    @ApiOperation(value = "获取用户偏好", notes = "获取用户的偏好设置")
    @GetMapping("/preferences/{userId}")
    public Result<List<UserPreference>> getUserPreferences(
            @ApiParam(value = "用户ID", required = true) @PathVariable Long userId) {
        try {
            List<UserPreference> preferences = userBehaviorService.getUserPreferences(userId);
            return Result.success(preferences);
        } catch (Exception e) {
            log.error("获取用户偏好失败: userId={}", userId, e);
            return Result.fail("获取用户偏好失败");
        }
    }

    @ApiOperation(value = "分析用户偏好", notes = "重新分析并更新用户偏好")
    @PostMapping("/preferences/analyze/{userId}")
    public Result<Void> analyzeUserPreferences(
            @ApiParam(value = "用户ID", required = true) @PathVariable Long userId) {
        try {
            userBehaviorService.analyzeUserPreferences(userId);
            return Result.success(null);
        } catch (Exception e) {
            log.error("分析用户偏好失败: userId={}", userId, e);
            return Result.fail("分析用户偏好失败");
        }
    }

    @ApiOperation(value = "获取热门内容", notes = "根据用户行为获取热门内容")
    @GetMapping("/hot/{actionType}")
    public Result<List<Map<String, Object>>> getHotContent(
            @ApiParam(value = "行为类型", required = true) @PathVariable String actionType,
            @ApiParam(value = "统计天数") @RequestParam(defaultValue = "7") Integer days,
            @ApiParam(value = "数量限制") @RequestParam(defaultValue = "50") Integer limit) {
        try {
            List<Map<String, Object>> hotContent = userBehaviorService.getHotContent(actionType, days, limit);
            return Result.success(hotContent);
        } catch (Exception e) {
            log.error("获取热门内容失败: actionType={}", actionType, e);
            return Result.fail("获取热门内容失败");
        }
    }

    @ApiOperation(value = "获取相似用户", notes = "获取与指定用户相似的用户列表")
    @GetMapping("/similar-users/{userId}")
    public Result<List<Map<String, Object>>> getSimilarUsers(
            @ApiParam(value = "用户ID", required = true) @PathVariable Long userId,
            @ApiParam(value = "数量限制") @RequestParam(defaultValue = "10") Integer limit) {
        try {
            List<Map<String, Object>> similarUsers = userBehaviorService.getSimilarUsers(userId, limit);
            return Result.success(similarUsers);
        } catch (Exception e) {
            log.error("获取相似用户失败: userId={}", userId, e);
            return Result.fail("获取相似用户失败");
        }
    }

    @ApiOperation(value = "计算用户相似度", notes = "计算两个用户之间的相似度")
    @GetMapping("/similarity")
    public Result<Double> calculateUserSimilarity(
            @ApiParam(value = "用户ID1", required = true) @RequestParam Long userId1,
            @ApiParam(value = "用户ID2", required = true) @RequestParam Long userId2) {
        try {
            Double similarity = userBehaviorService.calculateUserSimilarity(userId1, userId2);
            return Result.success(similarity);
        } catch (Exception e) {
            log.error("计算用户相似度失败: userId1={}, userId2={}", userId1, userId2, e);
            return Result.fail("计算相似度失败");
        }
    }
}
